const util = require('../../utils/util.js');
const api = require('../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    receiveSuccess:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let uid= wx.getStorageSync('newUid');
    let isReceive=wx.getStorageSync('isReceive');
    this.setData({
      receiveSuccess:isReceive
    })
    console.log(uid);
    if(uid!==''){
      this.sendCoupons(uid,2);
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 发送优惠券
  sendCoupons(userID,type){
    let that=this;
    util.requestApi(api.sendCoupons, {
        userID: userID,
        type:type
    }).then(function (res) {
        if (res.code === 200) {
          if(type===2){
            wx.setStorageSync('uid',userID);
          }else{
            wx.showToast({
              title: '领取成功',
              icon: 'success',
              duration: 2000
            });
            wx.setStorageSync('isReceive',1);
            that.setData({
              receiveSuccess:1
            });
          }
        } else {
          if(type===1){
            wx.showModal({
              title: '提示',
              content: '领取失败'
            })
          }
        }
    });
  },
  // 领取优惠券
  toTeceive(){
    let userID= wx.getStorageSync('userID');
    let isReceive=wx.getStorageSync('isReceive');
    if(!isReceive){
      this.sendCoupons(userID,1);
    }
  },
  goGoods(){
    wx.redirectTo({
      url: '/pages/goods/goods?id=201',
    })
  }
})